package com.csu.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.annotation.SaMode;
import com.csu.common.CommonResponse;
import com.csu.service.ChatService;
import com.csu.service.HeadPictureService;
import com.csu.service.RichTextService;
import com.csu.service.UserService;
import com.csu.util.MyWebSocket;
import com.csu.vo.ChatInfoVo;
import com.csu.vo.ChatVo;
import com.csu.vo.ClassMemberVo;
import jakarta.websocket.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 *聊天功能的实现
 */
@RestController
public class ChatController {
    @Autowired
    private ChatService chatService;
    @Autowired
    private RichTextService richTextService;

    @Autowired
    private UserService userService;
    @Autowired
    private HeadPictureService headPictureService;
    private static String imgUrl = "http://106.53.100.120:80/img/ql.jpg";

    /** 改对话标题 */
    @PutMapping("/chats/{chatId}/chatTitle")
    //@SaIgnore
    public CommonResponse<String> updateChatTitle(@PathVariable("chatId") int chat_id, @RequestParam("userId") int user_id,
                                                    @RequestBody Map<String,String> jsonData){
        //判断他是不是群主
        if (chatService.isGroupOwner(chat_id,user_id)){
            String msg = chatService.updateChatTitle(chat_id, jsonData.get("chatTitle"));
            if (msg.equals("success"))
                return CommonResponse.createForSuccess("SUCCESS","对话标题修改成功！");
            else
                return CommonResponse.createForError(msg);
        }else
            return CommonResponse.createForError("你不具有此权限！");
    }

    /** 删除对话 */
    @DeleteMapping("/chats/{chatId}/{userId}")
    //@SaCheckRole(value = {"parent", "student", "teacher"}, mode = SaMode.OR)
    public CommonResponse<String> deleteChat(@PathVariable("chatId") int chatId,@PathVariable("userId") int userId){
        if (chatService.isGroupOwner(chatId, userId)){
            System.out.println("chatId"+chatId);
            int msgCount = chatService.deleteChat(chatId);
            if (msgCount == 1)
                return CommonResponse.createForSuccess("SUCCESS","删除成功！");
            else
                return CommonResponse.createForError("删除异常，请联系管理员！");
        }else
            return CommonResponse.createForError("您无此权限，请联系群主！");
    }

    /** 获取班级成员 */
    @GetMapping("/users/classmember")
    //@SaCheckRole(value = {"parent", "student", "teacher"}, mode = SaMode.OR)
    public CommonResponse<List<ClassMemberVo>> getClassMember(@RequestParam("classId") int classId){
        List<ClassMemberVo> classMemberVos = userService.getClassMember(classId);
            return CommonResponse.createForSuccess("SUCCESS",classMemberVos);
    }
    /**
     * 获取聊天列表
     */
    @GetMapping("/chats")
    //@SaCheckRole(value = {"parent", "student", "teacher"}, mode = SaMode.OR)
    public CommonResponse<List<ChatVo>> getChatList(@RequestParam("userId") int userId){
        List<ChatVo> chatVos = chatService.getChatList(userId);
        if (!chatVos.isEmpty())
            return CommonResponse.createForSuccess("SUCCESS",chatVos);
        else
            return CommonResponse.createForError("聊天列表为空!");
    }
    /**
     * 创建私聊
     */
    @PutMapping("/chats/privite")
    //@SaIgnore
    public CommonResponse<ChatVo> createPrivateChat(@RequestParam("recipientId") int userId,@RequestParam("senderId") int senderId){
        ChatVo chatVo = chatService.isExistPrivateChat(senderId,userId);
        if (chatVo != null){
            return CommonResponse.createForSuccess("SUCCESS",chatVo);
        }else {
            //传过来的userId是接受者
            int recipient = userId;
            //获取私聊的接收方的名字
            String groupName = userService.getUsernameByUserId(recipient);

            int chatId = chatService.createChat(senderId,groupName,0);
            chatVo = new ChatVo();
            chatVo.setGroupName(groupName);
            chatVo.setChatId(chatId);
            chatVo.setImgurl(headPictureService.getHeadPicturePathOfUser(recipient));
            //添加用户和聊天的绑定关系
            int msgCount = chatService.addBoundBetweenUserAndChat(recipient,chatId);
            chatService.addBoundBetweenUserAndChat(senderId,chatId);
            if (msgCount == 1)
                return CommonResponse.createForSuccess("SUCCESS",chatVo);
            else
                return CommonResponse.createForError("创建私聊失败！");
        }
    }
    /**
     * 创建群聊
     */
    @PutMapping("/chats/group")
    //@SaIgnore
    public CommonResponse<ChatVo> createGroupChat(@RequestBody List<Integer> userList,@RequestParam("senderId") int senderId){
        String groupName = userService.getUsernameByUserId(senderId);
        for (int recipientId : userList){
            groupName +="," +userService.getUsernameByUserId(recipientId);
        }
        //创建群聊的信息
        int chatId = chatService.createChat(senderId,groupName,1);
        //添加绑定关系
        int msgCount = chatService.addBoundBetweenUserAndChat(senderId,chatId);
        for (int recipientId : userList){
            chatService.addBoundBetweenUserAndChat(recipientId,chatId);
        }
        //设置返回前端的VO
        ChatVo chatVo = new ChatVo();
        chatVo.setChatId(chatId);
        chatVo.setGroupName(groupName);
        chatVo.setImgurl(imgUrl);
        if (msgCount == 1)
            return CommonResponse.createForSuccess("SUCCESS",chatVo);
        else
            return CommonResponse.createForError("创建群聊失败！");
    }
    /**
     * 退出聊天列表,关闭webSocket
     */
    @PostMapping("/chat/closeWebSocket")
    //@SaIgnore
    public CommonResponse<String> closeWebSocket(@RequestParam("userId") int userId){
        Session session = MyWebSocket.sessionPool.get(userId);
        try {
            session.close();
        } catch (IOException e) {
            System.out.println(e.getMessage());
            CommonResponse.createForError("关闭session失败！");
        }
        return CommonResponse.createForSuccess("SUCCESS","关闭session成功！");
    }
    /**
     * 获取聊天记录
     */
    @GetMapping("/chats/{chatId}")
    //@SaIgnore
    public CommonResponse<List<ChatInfoVo>> getChatInfoList(@PathVariable("chatId") int chatId){
        List<ChatInfoVo> chatInfoVos = chatService.getChatInfoList(chatId);
        System.out.println(chatInfoVos);
        if (!chatInfoVos.isEmpty())
            return CommonResponse.createForSuccess("SUCCESS",chatInfoVos);
        else
            return CommonResponse.createForError("聊天记录为空!");
    }
    /**
     * 更新webSocket建立的chatId
     */
    @PostMapping("/chat/updateChatId/{userId}/{chatId}")
    //@SaIgnore
    public CommonResponse<String> updateChatIdOfWebSocket(@PathVariable("userId") int userId,@PathVariable("chatId") int chatId){
        MyWebSocket.userMap.replace(userId,chatId);
        return CommonResponse.createForSuccess("SUCCESS","更新数据:userId:"+userId+"；chatId:"+chatId);
    }
    /**
     * 用户查看聊天详情，取消unreadCount
     */
    @PostMapping("/chat/watchChat/{userId}/{chatId}")
    //@SaIgnore
    public CommonResponse<String> watchChat(@PathVariable("userId") int userId,@PathVariable("chatId") int chatId){
        Integer msgCount = chatService.watchChat(userId, chatId);
        if (msgCount == 1)
            return CommonResponse.createForSuccess("SUCCESS","更新成功！");
        else
            return CommonResponse.createForError("更新失败!");
    }

    /**
     * 上传语音与回显
     */
    @PostMapping("/file/voice")
    public CommonResponse<String> postVoice(@RequestParam("voiceFile")MultipartFile voiceFile) throws IOException {
        System.out.println("reached");
        String requestPath = richTextService.downloadFile(voiceFile,2);
        if (requestPath.isEmpty())
            return CommonResponse.createForError("图片上传失败！");
        else
            return CommonResponse.createForSuccess("SUCCESS",requestPath);
    }
}
